// @ts-ignore
import IpcMain = Electron.IpcMain
import { dialog } from 'electron'
import fs from 'fs'

const json2csv = require('json2csv')

function valueToString(value: number | string) {
  if (typeof value === 'number') {
    return value.toString()
  }
  return value
}

async function exportToCsv(dataList: string) {
  return new Promise<boolean>((resolve) => {
    const list = JSON.parse(dataList)

    const fields = Object.keys(list[0]).map((key) => {
      return {
        label: key,
        value: key,
        stringify: valueToString
      }
    })

    const csv = json2csv.parse(list, { fields: fields })

    const options = {
      title: '导出为CSV',
      defaultPath: 'export.csv',
      filters: [
        { name: 'CSV Files', extensions: ['csv'] } // 保存文件类型为 CSV
      ]
    }
    let success = true
    dialog
      .showSaveDialog(options)
      .then((result) => {
        if (!result.canceled && result.filePath) {
          fs.writeFile(result.filePath, csv, (error) => {
            if (error) {
              success = false
            }
          })
        } else {
          success = false
        }
      })
      .finally(() => {
        resolve(success)
      })
  })
}

export function register(ipcMain: IpcMain) {
  // @ts-ignore
  ipcMain.handle('exportToCsv', function (event, dataList) {
    return exportToCsv(dataList)
  })
}
